package wallet

import (
	"context"
	"go.uber.org/zap"
	gamepb "navi-mumbai/app/rpc/game/pb"
	"navi-mumbai/app/rpc/wallet/pb"
	"navi-mumbai/common/ctxdata"
	"navi-mumbai/common/xerr"

	"navi-mumbai/app/api/business/internal/svc"
	"navi-mumbai/app/api/business/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserTransferToGameWalletLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserTransferToGameWalletLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserTransferToGameWalletLogic {
	return &UserTransferToGameWalletLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserTransferToGameWalletLogic) UserTransferToGameWallet(req *types.UserTransferToGWalletReq) (resp *types.UserTransferToGWalletResp, err error) {
	uid := ctxdata.GetUidFromCtx(l.ctx)
	if uid != req.Uid {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.AuthFail, "no privilege")
	}

	// 创建转账流水
	var in pb.UserCreateTransferToGameReq
	in = pb.UserCreateTransferToGameReq{
		Uid:         req.Uid,
		MoneyType:   req.MoneyType,
		ProviderId:  req.ProviderId,
		MoneyAmount: req.MoneyAmount,
	}
	var rsp1 *pb.UserCreateTransferToGameResp
	rsp1, err = l.svcCtx.WalletUsersRpc.UserCreateTransferToGame(l.ctx, &in)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return &types.UserTransferToGWalletResp{}, err
	}
	// 请求G端转账
	var in2 gamepb.UserTransferToGWalletReq
	in2 = gamepb.UserTransferToGWalletReq{
		Uid:         req.Uid,
		MoneyType:   req.MoneyType,
		MoneyAmount: rsp1.MoneyAmount,
		ProviderId:  req.ProviderId,
		FlowNo:      rsp1.FlowNo,
	}
	var rsp2 *gamepb.UserTransferToGWalletResp
	rsp2, err = l.svcCtx.GameWalletRpc.UserTransferToGWallet(l.ctx, &in2)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return &types.UserTransferToGWalletResp{}, err
	}
	// 更新转账流水
	var in3 pb.UpdateTransferToGameResultReq
	in3 = pb.UpdateTransferToGameResultReq{
		Uid:            req.Uid,
		FlowNo:         rsp1.FlowNo,
		State:          rsp2.State,
		ExternalFlowNo: rsp2.ExternalFlowNo,
		MoneyType:      rsp2.MoneyType,
		NewBalance:     rsp2.NewBalance,
		OldBalance:     rsp2.OldBalance,
		ErrMsg:         rsp2.ErrMsg,
	}

	_, err = l.svcCtx.WalletUsersRpc.UpdateTransferToGameResult(l.ctx, &in3)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return &types.UserTransferToGWalletResp{}, err
	}
	resp = &types.UserTransferToGWalletResp{
		MoneyType: rsp1.MoneyType,
		Balance:   rsp1.Balance,
	}
	if rsp2.ErrMsg != "" {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.WalletTransferError, rsp2.ErrMsg)
	}
	return
}
